﻿using AutoMapper;
using DTcms.Core.API.Filters;
using DTcms.Core.Common.Emum;
using DTcms.Core.Common.Extensions;
using DTcms.Core.Common.Helper;
using DTcms.Core.IServices;
using DTcms.Core.Model.Models;
using DTcms.Core.Model.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace DTcms.Core.API.Controllers
{
    /// <summary>
    /// 系统参数配置
    /// </summary>
    [Area("api")]
    [Route("api/admin/setting")]
    [ApiController]
    public class SettingController : ControllerBase
    {
        private readonly ISysConfigService _sysConfigService;
        private readonly ISmsService _smsService;
        private readonly IMapper _mapper;
        /// <summary>
        /// 构造函数依赖注入
        /// </summary>
        public SettingController(ISysConfigService sysConfigService, ISmsService smsService, IMapper mapper)
        {
            _sysConfigService = sysConfigService;
            _smsService = smsService;
            _mapper = mapper;
        }

        #region 管理员调用接口==========================
        /// <summary>
        /// 获取系统配置
        /// 示例：/api/admin/setting/sysconfig
        /// </summary>
        [HttpGet("{type}")]
        [Authorize]
        [AuthorizeFilter("Setting", ActionType.View, "type")]
        public async Task<IActionResult> Get([FromRoute] ConfigType type)
        {
            var model = await _sysConfigService.QueryAsync<SysConfig>(x => x.Type != null && x.Type.ToLower() == type.ToString(), WriteRoRead.Write);
            if (model == null)
            {
                //如果找不到，则返回统一错误消息
                return BadRequest(ResponseMessage.Error($"系统参数{type}无法找到。"));
            }
            if (model.Type == ConfigType.SysConfig.ToString())
            {
                return Ok(JsonHelper.ToJson<SysConfigDto>(model.JsonData));
            }
            else if (model.Type == ConfigType.MemberConfig.ToString())
            {
                return Ok(JsonHelper.ToJson<MemberConfigDto>(model.JsonData));
            }
            throw new ResponseException($"找不到{type}配置返回类型");
        }

        /// <summary>
        /// 修改系统配置
        /// 示例：/api/admin/setting/sysconfig
        /// </summary>
        [HttpPut("sysconfig")]
        [Authorize]
        [AuthorizeFilter("Setting", ActionType.Edit, "SysConfig")]
        public async Task<IActionResult> Update([FromBody] SysConfigDto modelDto)
        {
            var model = await _sysConfigService.QueryByTypeAsync(ConfigType.SysConfig, WriteRoRead.Write);
            if (model == null)
            {
                //如果找不到，则返回统一错误消息
                return BadRequest(ResponseMessage.Error($"系统配置不存在或已删除。"));
            }
            model.JsonData = JsonHelper.GetJson(modelDto);
            var result = await _sysConfigService.UpdateAsync<SysConfig>(model);
            if (!result)
            {
                //抛出自定义异常错误
                throw new ResponseException("保存过程中发生错误。");
            }
            return NoContent();
        }

        /// <summary>
        /// 修改会员配置
        /// 示例：/api/admin/setting/memberconfig
        /// </summary>
        [HttpPut("memberconfig")]
        [Authorize]
        [AuthorizeFilter("Setting", ActionType.Edit, "MemberConfig")]
        public async Task<IActionResult> Update([FromBody] MemberConfigDto modelDto)
        {
            var model = await _sysConfigService.QueryByTypeAsync(ConfigType.MemberConfig, WriteRoRead.Write);
            if (model == null)
            {
                //如果找不到，则返回统一错误消息
                return BadRequest(ResponseMessage.Error($"会员配置不存在或已删除。"));
            }
            model.JsonData = JsonHelper.GetJson(modelDto);
            var result = await _sysConfigService.UpdateAsync<SysConfig>(model);
            if (!result)
            {
                //抛出自定义异常错误
                throw new ResponseException("保存过程中发生错误。");
            }
            return NoContent();
        }

        /// <summary>
        /// 获取短信账户数量
        /// send:已发送数量
        /// quantity:余额
        /// 示例：/api/admin/setting/sms/account/quantity
        /// </summary>
        [HttpGet("sms/account/{type}")]
        [Authorize]
        [AuthorizeFilter("Setting", ActionType.Edit, "SysConfig")]
        public async Task<IActionResult> GetSmsQuantity([FromRoute] string type)
        {
            if (!type.IsNotNullOrEmpty())
            {
                throw new ResponseException("查询参数有误");
            }
            var result = new SmsResultDto();
            switch (type)
            {
                case "quantity":
                    result = await _smsService.GetAccountQuantity();
                    break;
                default:
                    result = await _smsService.GetSendQuantity();
                    break;
            }
            if (result.Code == null || !result.Code.Equals("100"))
            {
                throw new ResponseException("查询短信账户失败");
            }
            return Ok(result);
        }

        /// <summary>
        /// 获取官方动态
        /// 示例：/api/admin/setting/official/notice
        /// </summary>
        [HttpGet("official/notice")]
        [Authorize]
        [ApiExplorerSettings(IgnoreApi = true)]
        public async Task<IActionResult> GetNotice([FromRoute] ConfigType type)
        {
            var result = await RequestHelper.GetAsync("http://www.dtcms.net/notice.ashx");
            return Ok(result);
        }
        #endregion

        #region 前台调用接口============================
        /// <summary>
        /// 获取系统基本配置
        /// 示例：/api/client/setting/sysconfig
        /// </summary>
        [HttpGet("/api/client/setting/{type}")]
        public async Task<IActionResult> ClientGetSysConfig([FromRoute] ConfigType type)
        {
            var configType = type;
            if (type == ConfigType.UploadConfig)
            {
                configType = ConfigType.SysConfig;
            }
            var model = await _sysConfigService.QueryByTypeAsync(configType);
            if (model == null)
            {
                return BadRequest(ResponseMessage.Error($"找不到{type}配置返回类型"));
            }
            switch (type)
            {
                case ConfigType.SysConfig:
                    return Ok(JsonHelper.ToJson<SysConfigClientDto>(model.JsonData));
                case ConfigType.UploadConfig:
                    var sysConfig = JsonHelper.ToJson<SysConfigDto>(model.JsonData);
                    var uploadConfig = _mapper.Map<UploadConfigDto>(sysConfig);
                    return Ok(uploadConfig);
                default:
                    return BadRequest(ResponseMessage.Error($"找不到{type}配置返回类型"));
            }
        }
        #endregion
    }
}
